// create angular app
var UserDetails = angular.module(' ', []);
// We use the directive to recompile for
UserDetails.directive('compileTemplate', function($compile, $parse){
    return {
        link: function(scope, element, attr){
            var parsed = $parse(attr.ngBindHtml);
            function getStringValue() { return (parsed(scope) || '').toString(); }

            //Recompile if the template changes
            scope.$watch(getStringValue, function() {
                $compile(element, null, -9999)(scope);  //The -9999 makes it skip directives so that we do not recompile ourselves
            });
        }         
    }
});
// create angular controller
UserDetails.controller('MainWindow',function($scope,$http,$sce,$interval) 
{
	$scope.checkSession = function(wnd){					
		$scope.typeofGetMsgs = 1;
		MainInterval = null;
		TopicInterval = null;
			if( wnd == "mainWindow")
			{
				MainInterval = $interval(function(){	$scope.CheckIfThereIsNewMessages();	},10000,0);
			}
			else if ( wnd == "TopicWindow")
			{
				TopicInterval = $interval(function(){	$scope.CheckIfThereIsNewTopics(5);	},10000,0);
			
			}

			$http.post("sessioncheck", {Type:wnd}).then(function(response) 
			{
				
			 	$scope.typeofGetMsgs = 1; // all
				var array = response.data;
		    	if (response.data.Answer == "Success")
				{
		    		$scope.Nick = response.data.Nick;
		    		$scope.Topic = response.data.Topic;
				}
		    	else
		    	{
		    		var l = response.data.Location;
		    		window.location = l.toString();
		    		
		    	}
	
	        });
		
	};
	$scope.messageinsert = function()
	{
		var str = $scope.message_text;
		if(str.length > 140)
		{
			$scope.err= "Text length need to be up to 140";
		}
		else
		{
			var temp = $scope.typeofGetMsgs;
			
			$http.post("messageinsert", {Text:$scope.message_text ,Type:1}).then(function(response) {
				$scope.btnDiscover((temp*10)+ 3);
				$scope.message_text =""; // reset message text

			});
		}

	};
	$scope.btnRepublish = function(x)
	{
		var temp = $scope.typeofGetMsgs;
		$http.post("messageinsert", {Text:x.Text ,Type:2,MsgID:x.id}).then(function(response) {
			$scope.btnDiscover((temp*10)+ 3);
		});
	}
	$scope.btnRepublishComment = function(x)
	{
		var temp = $scope.typeofGetMsgs;
		$http.post("messageinsert", {Text:x.Text ,Type:3,MsgID:x.id}).then(function(response) {
			$scope.btnDiscover((temp*10)+ 3);
		});
	};
	$scope.btnFollow= function(x)
	{
		$http.post("followuser", {UsernameToFollow:x.Username}).error(function(response) {
        	alert("Error");
		}).then(function(response){
			$scope.btnDiscover($scope.typeofGetMsgs);// update the message without restart
		});
	}
	$scope.btnUnFollow= function(x)
	{
		$http.post("unfollowuser", {UsernameToFollow:x.Username}).error(function(response) {
			alert("Error");
		}).then(function(response){
			$scope.btnDiscover($scope.typeofGetMsgs); // update the message without restart
		});
	
	}
	$scope.btnComment=function(x)
	{
		x.showComments = !x.showComments;
		
	};
	$scope.getCommentPerMessage = function(x)
	{
		var tempComments = [];
		//var param= $scope.buildStringToGetMsgsComments(r);
		$http.post("getcomments", {id:x.id}).then(function(response){
			
			for (x in response.data)
			{
				tempComments.push( response.data[x] );
			}
			
			
        });
		return tempComments;
		
	}
	$scope.btnReply = function(x,type)
	{
		var saveid=x.id;
		//reply to msg id
		$http.post("replymsgs", {"MessageID" : x.id, "Text" : x.message_text_reply}).then( function(response){
			if( type == 5){
				$scope.btnDiscover(5); // update the message without restart
			}else{
				$scope.btnDiscover($scope.typeofGetMsgs);
			}
			x.message_text_reply = "";
		});
		
	};
	$scope.btnDiscover = function(type)
	{
		if ((type%10) != 3){ // type 3 is to handle with the request to show the message after is posted
			$scope.typeofGetMsgs = type; //we save the flag of the currect show message
		}
		$scope.setDiscoverOptionText();
		$http.post("getmsgs", {Type:type}).then(function(response){
			$scope.result = [];
			for (x in response.data)
			{
				$scope.result.push( response.data[x] );
				$scope.result[x].theComments = $scope.getCommentPerMessage( response.data[x] );
			}
        });
	}
	$scope.btnShowMemberProfile = function(Nickname)
	{
		if( MainInterval != null )
			$interval.cancel(MainInterval);
		if ( TopicInterval == null)
			$interval.cancel(TopicInterval);
		//View a member's profile
		$http.post("viewmyprofile", {"Nickname" : Nickname}).then( function(response){
			window.location = "User.html";
		});
	};
	$scope.TurnToHtml = function(text){
		return ($sce.trustAsHtml(text));
	}
	$scope.btnTopicsLoad = function(topic){
		if( MainInterval != null )
			$interval.cancel(MainInterval);
		if ( TopicInterval == null)
			$interval.cancel(TopicInterval);
		//View a member's profile
		$http.post("settopic", {"Text" : topic}).success( function(response){
			window.location = "Topic.html";
		});
	}
	$scope.CheckIfThereIsNewTopics = function(type){
		$http.post("getmsgs", {Type:type}).then(function(response){
			$scope.tempresult = [];
			
			for (x in response.data)
			{
				
				$scope.tempresult.push( response.data[x] );
				$scope.tempresult[x].theComments = $scope.getCommentPerMessage( response.data[x] );
			}
		
			if ($scope.result.length != $scope.tempresult.length || $scope.result[0].id != $scope.tempresult[0].id) // if there update with new topic
			{
				$scope.ShowUpdatesButtonFlag = true;
			}
			else // no change - hide button
			{
				$scope.ShowUpdatesButtonFlag = false;
			}

			
        });
	}
	$scope.UpdateTopicsMessages=function()
	{
		$scope.result = $scope.tempresult;
		$scope.ShowUpdatesButtonFlag = false;
	}

	$scope.CheckIfThereIsNewMessages = function()
	{
		//alert($scope.typeofGetMsgs);
		//$scope.btnDiscover($scope.typeofGetMsgs);
		$scope.setDiscoverOptionText();
		$http.post("getmsgs", {Type:$scope.typeofGetMsgs}).then(function(response){
			$scope.tempMsgresult = [];
			for (x in response.data)
			{
				// if it the same id in place x - change it
				if (response.data[x].id != $scope.result[x].id )
				{
					$scope.result[x] = response.data[x];
					$scope.result[x].theComments = $scope.getCommentPerMessage( response.data[x] );
				}
	
				
			}
		});
       
	}
	$scope.setDiscoverOptionText= function()
	{
		if($scope.typeofGetMsgs == 1)
			$scope.DiscoverOptionText = "New Messages";
		else if($scope.typeofGetMsgs == 2)
			$scope.DiscoverOptionText = "Messages Of Users Who I Follow";
		else if($scope.typeofGetMsgs == 6)
			$scope.DiscoverOptionText = "My Messages";
	}
	
});